<script setup>
import { reactive, ref, computed, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useCrudTable } from '@/composables/useCrudTable'
// Mock 数据
// 初始化数据
const {
    rows,
    multipleSelectionIds,
    remove,
    batchDelete,
    handleSelectionChange,
    handleSortChange,
} = useCrudTable([
    { id: 1, name: 'Alice', email: 'alice@example.com', role: 'admin', createdAt: Date.now() - 86400000 * 3 },
    { id: 2, name: 'Bob', email: 'bob@example.com', role: 'editor', createdAt: Date.now() - 86400000 * 2 },
    { id: 3, name: 'Carol', email: 'carol@example.com', role: 'viewer', createdAt: Date.now() - 86400000 * 7 },
])

const columns = [
    { prop: 'id', label: 'ID', width: 80, sortable: 'custom' },
    { prop: 'name', label: '姓名' },
    { prop: 'email', label: '邮箱' },
    {
        prop: 'role',
        label: '角色',
    },
    {
        prop: 'createdAt',
        label: '创建时间',
        sortable: 'custom',
        formatter: (val) => new Date(val).toLocaleString(),
    },
]
const pagination = reactive({ pageNo: 1, pageSize: 10 })
watch([() => pagination.pageNo, () => pagination.pageSize], () => {
    console.log('当前页:', pagination.pageNo, '每页条数:', pagination.pageSize)
})
// 查询（关键词，角色）
const query = reactive({ keyword: '', role: '' })
//控制对话框
const dialog = reactive({
    visible: false,
    mode: 'create',
    editId: 0,
})
// 表单数据及校验
const formRef = ref()
const form = reactive({
    name: '',
    email: '',
    role: '',
})
const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
    ],
    role: [{ required: true, message: '请选择角色', trigger: 'change' }],
}
// 打开新建
function openCreate() {
    dialog.mode = 'create'
    dialog.editId = null
    Object.assign(form, { name: '', email: '', role: '' })
    dialog.visible = true
}

// 打开编辑
function openEdit(row) {
    dialog.mode = 'edit'
    dialog.editId = row.id
    Object.assign(form, { name: row.name, email: row.email, role: row.role })
    dialog.visible = true
}


// 提交
function submit() {
    formRef.value.validate((valid) => {
        if (!valid) return
        if (dialog.mode === 'create') {
            const maxId = rows.value.reduce((m, r) => Math.max(m, r.id), 0)
            rows.value.unshift({
                id: maxId + 1,
                name: form.name,
                email: form.email,
                role: form.role,
                createdAt: Date.now(),
            })
            ElMessage.success('新增成功')
        } else {
            const idx = rows.value.findIndex((r) => r.id === dialog.editId)
            if (idx > -1) {
                rows.value[idx] = { ...rows.value[idx], ...form }
                ElMessage.success('修改成功')
            }
        }
        dialog.visible = false
    })
}

</script>
<template>
    <div class="table-header">
        <el-button icon="plus" @click="openCreate" type="success" class="add-btn">
            新建
        </el-button>
        <el-button icon="delete" @click="batchDelete" type="danger" class="delete-btn"
            :disabled="!multipleSelectionIds.length"
        >
            批量删除
        </el-button>
        <el-input v-model="query.keyword" placeholder="请输入姓名" clearable class="search-input">
        </el-input>

        <el-select v-model="query.role" placeholder="请选择角色" clearable class="role-select">
            <el-option label="Admin" value="admin" />
            <el-option label="Editor" value="editor" />
            <el-option label="Viewer" value="viewer" />
        </el-select>

        <el-button type="primary" @click="handleSearch" icon="Search">
            搜索
        </el-button>
        <el-button @click="resetFilters" icon="Refresh">
            重置
        </el-button>

    </div>
    <el-table :data="rows" border stripe size="small" @selection-change="handleSelectionChange"
        @sort-change="handleSortChange" highlight-current-row>
        <el-table-column type="selection" width="48" />
        <el-table-column v-for="col in columns" :key="col.prop" v-bind="col">
            <template #default="scope">
                <span>
                    {{ col.formatter ? col.formatter(scope.row[col.prop]) : scope.row[col.prop] }}
                </span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
                <el-button size="small" type="primary" link @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" link @click="remove(row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <el-dialog v-model="dialog.visible" :title="dialog.mode === 'create' ? '新建用户' : '编辑用户'" width="520px">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="88px">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="form.name" placeholder="张三" clearable />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="user@example.com" clearable />
            </el-form-item>
            <el-form-item label="角色" prop="role">
                <el-select v-model="form.role" placeholder="请选择">
                    <el-option label="Admin" value="admin" />
                    <el-option label="Editor" value="editor" />
                    <el-option label="Viewer" value="viewer" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submit">保存</el-button>
            </span>
        </template>
    </el-dialog>
    <div class="pagination-wrapper">
        <el-pagination background layout="total, sizes, prev, pager, next, jumper" 
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagination.pageSize" :current-page="pagination.No" :total="rows.length"
        @size-change="(s) => (pagination.pageSize = s)" @current-change="(p) => (pagination.No = p)" />

    </div>
</template>
<style scoped>
.table-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    padding: 12px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-input {
    width: 240px;
}

.role-select {
    width: 140px;
}
.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* .add-btn { margin-left: auto; } */
.delete-btn{
    margin-right: 20px;
}
</style>